package com.adcc.ags.agent.healthcheck;

import com.adcc.utility.log.Log;
import com.codahale.metrics.health.HealthCheck;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;

import java.util.Map;

/**
 * 内存健康检查
 */
public class MemoryHealthCheck extends HealthCheck {

    @Override
    protected Result check() {
        Sigar sigar = null;
        try{
            sigar = new Sigar();
            Mem mem = sigar.getMem();
            double dUsed = mem.getUsedPercent();
            double dFree = mem.getFreePercent();
            Map<String,Double> map = Maps.newHashMapWithExpectedSize(2);
            map.put("used",dUsed);
            map.put("free",dFree);
            return Result.healthy(new ObjectMapper().writeValueAsString(map));
        }catch (Exception ex){
            Log.error(MemoryHealthCheck.class.getName(),"check() error",ex);
            return Result.unhealthy(ex.fillInStackTrace());
        }finally {
            if(sigar != null){
                sigar.close();
            }
        }
    }
}
